import { ConfigObject, createMathExpr } from 'svg-captcha';
import { v4 as feidao_uuid } from 'uuid';
import { close, open, set } from '../_redis';
import log from '../logger/log';

export interface IWebResult {
	data?: any;
	buff?: Buffer;
	cookie?: { [name: string]: string };
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

/**
 * 生成数字计算的验证码
 * @param cookie cookie对象
 * @param options 生成验证码参数
 * @param options.width 验证码图片宽度
 * @param options.height 验证码图片高度
 * @param options.fontSize 验证码文字大小
 * @param options.color 字的颜色，false时（默认）黑色，true时颜色随机
 * @param options.inverse false为黑字（默认），true为白字，（仅当参数color为false时该参数有效）
 * @param options.noise 干扰线的条数，默认为1
 * @param options.background 背景色
 */
export default async function math_expr(cookie: { uk: string; }, options: ConfigObject) {
	const client = open();
	try {
		const uk = cookie.uk || feidao_uuid();
		const { data, text } = createMathExpr(options);
		log('saving captcha: key=' + uk + ', value=' + text);
		await set(client, uk, text);
		return cookie.uk ? {
			content_type: 'svg',
			data
		} : {
			content_type: 'svg',
			cookie: {
				uk
			},
			data
		} as IWebResult;
	} finally {
		close(client);
	}
}
